/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.shwread.android.qysw10000182.R;
import com.shwread.httpsdk.http.download.DownLoadPicture;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import logic.bean.EnterpriseColumn;
import logic.util.FileUtil;
import logic.util.SDcardUtil;
import logic.util.ScreenUtil;
import logic.util.Util;


/**
 * @Project： Lqyd_Android
 * @Title：EnterpriseNewsActivity
 * @Description：企业资讯详情页面
 * @Author：wayne
 * @Date：2014年8月23日下午2:37:06
 */
public class EnterpriseNewsActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener
{
	private Context          mContext;
	
	private TextView         tvTitle;
	private Button           btnBack;
	private TextView         tvNewsTitle;
	private TextView         tvNewsAuthor;
	private TextView         tvNewsTime;
	private TextView         tvNewsContent;
	
	private Drawable         defaultDrawable;
	
	private EnterpriseColumn info;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.enterprise_news_detail);
		mContext = this;
		//默认图片，无图片或没加载完显示此图片
		defaultDrawable = getResources().getDrawable(R.drawable.enterprise_default);
		
		initView();
		setListener();
	}
	
	@Override
	protected void onResume() {
		info = (EnterpriseColumn) getIntent().getSerializableExtra("EnterpriseColumn");
		if (null != info)
		{
			initData();
		}
		super.onResume();
	}
	
	void initData() {
		tvNewsTitle.setText(info.getTitle());
		if (Util.isEmpty(info.getSource()))
		{
			tvNewsAuthor.setVisibility(View.GONE);
		}
		else
		{
			tvNewsAuthor.setVisibility(View.VISIBLE);
			tvNewsAuthor.setText(info.getSource());
		}
		tvNewsTime.setText(Util.getTimeByDuration(Util.getStringtoDate(info.getPublicTime()).getTime()));
		Spanned sp = Html.fromHtml(info.getContent(), new HtmlImageGetter(tvNewsContent, defaultDrawable), null);
		tvNewsContent.setText(sp);
	}
	
	void initView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		tvNewsTitle = (TextView) findViewById(R.id.enterprise_news_detail_title);
		tvNewsAuthor = (TextView) findViewById(R.id.enterprise_news_detail_author);
		tvNewsTime = (TextView) findViewById(R.id.enterprise_news_detail_time);
		tvNewsContent = (TextView) findViewById(R.id.enterprise_news_detail_content);
		tvTitle.setText(getResources().getString(R.string.enterprise_news));
	}
	
	void setListener() {
		btnBack.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				this.finish();
				break;
			
			default:
				break;
		}
	}
	
	public class HtmlImageGetter
	        implements
	        ImageGetter
	{
		private TextView _htmlText;
		private Drawable _defaultDrawable;
		private String   TAG = "HtmlImageGetter";
		
		public HtmlImageGetter(TextView htmlText, Drawable defaultDrawable) {
			_htmlText = htmlText;
			_defaultDrawable = defaultDrawable;
		}
		
		@Override
		public Drawable getDrawable(String imgUrl) {
			
			String imgKey = String.valueOf(imgUrl.hashCode());
			String path = SDcardUtil.getImagePath().getPath();
			
			String imgX = imgUrl.substring(imgUrl.lastIndexOf(".") + 1, imgUrl.length());
			imgKey = path + "/" + imgKey + "." + imgX;
			
			if (FileUtil.exists(imgKey))
			{
				Drawable drawable = FileUtil.getImageDrawable(imgKey);
				if (drawable != null)
				{
					int multiple = (int) ((int) ScreenUtil.densityDpi / 160 * ScreenUtil.density);
					int height = drawable.getIntrinsicHeight() * multiple;
					if (height > ScreenUtil.screenHeight) height = ScreenUtil.screenHeight / 2;
					drawable.setBounds(0, 0, ScreenUtil.screenWidth - 100, height);
					return drawable;
				}
				else
				{
					base.tina.core.log.LogPrinter.d("fw", "load img:" + imgKey + ":null");
				}
			}
			
			URLDrawable urlDrawable = new URLDrawable(_defaultDrawable);
			new AsyncThread(urlDrawable).execute(imgKey, imgUrl);
			return urlDrawable;
		}
		
		private class AsyncThread
		        extends
		        AsyncTask<String, Integer, Drawable>
		{
			private String      imgKey;
			private URLDrawable _drawable;
			
			public AsyncThread(URLDrawable drawable) {
				_drawable = drawable;
			}
			
			@Override
			protected Drawable doInBackground(String... strings) {
				imgKey = strings[0];
				
				InputStream inps = DownLoadPicture.getInputStream(strings[1]);
				if (inps == null) return _drawable;
				
				saveFile(imgKey, inps);
				Drawable drawable = Drawable.createFromPath(imgKey);
				return drawable;
			}
			
			public void onProgressUpdate(Integer... value) {
				
			}
			
			@Override
			protected void onPostExecute(Drawable result) {
				_drawable.setDrawable(result);
				_htmlText.setText(_htmlText.getText());
			}
		}
		
		public File saveFile(String file, InputStream inputStream) {
			File f = null;
			OutputStream outSm = null;
			
			try
			{
				f = new File(file);
				String path = f.getParent();
				if (!FileUtil.exists(SDcardUtil.getImagePath().getPath()))
				{
					Log.e(TAG, "can't create dir:" + path);
					return null;
				}
				
				if (!f.exists())
				{
					f.createNewFile();
				}
				
				outSm = new FileOutputStream(f);
				byte[] buffer = new byte[1024];
				while ((inputStream.read(buffer)) != -1)
				{
					outSm.write(buffer);
				}
				outSm.flush();
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
				return null;
				
			}
			finally
			{
				try
				{
					if (outSm != null) outSm.close();
				}
				catch (IOException ex)
				{
					ex.printStackTrace();
				}
			}
			Log.v(TAG, "[FileUtil]save file:" + file + ":" + Boolean.toString(f.exists()));
			
			return f;
		}
		
		public class URLDrawable
		        extends
		        BitmapDrawable
		{
			
			private Drawable drawable;
			
			public URLDrawable(Drawable defaultDraw) {
				setDrawable(defaultDraw);
			}
			
			private void setDrawable(Drawable ndrawable) {
				if (ndrawable != null)
				{
					drawable = ndrawable;
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
					setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				}
			}
			
			@Override
			public void draw(Canvas canvas) {
				drawable.draw(canvas);
			}
		}
	}
}
